package tingshu.servlet.track;

import tingshu.repository.TrackRepo;
import tingshu.util.Log;
import tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@MultipartConfig
@WebServlet("/studio/track/upload.do")
public class UploadDoServlet extends HttpServlet {
    TrackRepo trackRepo = new TrackRepo();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);

        UserVO userVo = null;
        if (session != null) {
            userVo = (UserVO)session.getAttribute("currentUser");
        }

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/plain");
        PrintWriter writer = resp.getWriter();
        if (userVo == null) {
            Log.println("用户未登录");
            writer.println("必须登陆才能使用此功能！");
            return;
        }

        Log.println("登陆用户为" + userVo);
        req.setCharacterEncoding("UTF-8");
        String title = req.getParameter("title");
        Log.println("获取到的 title 是 " + title);

        Part track = req.getPart("track");
        String contentType = track.getContentType();
        Log.println("获取到的 type 是 " + contentType);

        InputStream inputStream = track.getInputStream();

        trackRepo.insert(userVo.uid,title,contentType,inputStream);
        Log.println("上传成功");

        writer.println("上传成功");
    }
}
